package com.ht.api.db;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * selectDB的StreamLoad配置
 * @author asq
 * @createTime 2024年12月26日 14:24:35
 */
@Slf4j
@Data
@Component
public class StreamLoadConfig implements Serializable {
	private static final long serialVersionUID = 1L;
	/** 主机地址 */
	private String feHost;
	/** 端口 */
	private int fePort = 8080;
	/** 数据库名称 */
	private String dbName;
	/** 用户名称 */
	private String username;
	/** 密码 */
	private String password;
	/** 每次写入条数 */
	private int batchSize = 100000;
	/** 超时时间 */
	private int timeoutSeconds = 600;
    
    @Autowired
    private Environment env;

    @PostConstruct
	public void init() {
		// 从 Spring 配置中获取数据源 URL
		String jdbcUrl = env.getProperty("spring.datasource.url");
		if (jdbcUrl != null) {
			// 解析 JDBC URL
			try {
				// 示例URL: jdbc:mysql://host:9030/dbname?param=value
				String urlWithoutPrefix = jdbcUrl.substring(jdbcUrl.indexOf("://") + 3);
				String hostPort = urlWithoutPrefix.substring(0, urlWithoutPrefix.indexOf("/"));
				String[] hostPortArr = hostPort.split(":");

				// 设置 host (需要把 9030 端口改为 8080)
				feHost = (hostPortArr[0]);

				// 设置数据库名
				String dbName = urlWithoutPrefix.substring(urlWithoutPrefix.indexOf("/") + 1);
				if (dbName.contains("?")) {
					dbName = dbName.substring(0, dbName.indexOf("?"));
				}
				this.dbName = (dbName);
			} catch (Exception e) {
				log.error("解析 JDBC URL 失败", e);
			}
		}

		// 设置用户名和密码
		username = (env.getProperty("spring.datasource.username"));
		password = (env.getProperty("spring.datasource.password"));
	}
}
